package com.service.atm;

import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import oracle.sql.CLOB;

import com.bpms.common.Base64;
import com.bpms.common.CommonUtil;
import com.bpms.common.Constant;
import com.bpms.common.DBOperation;
import com.bpms.common.JdbcWorker;
import com.bpms.common.Param;
import com.bpms.common.VO;
import com.bpms.common.VOList;
import com.bpms.esb.IService;
import com.bpms.esb.SV;
import com.service.util.BillPhoto;

/**
 * 1002 交易 进账单返回报文业务
 * 
 * @author menlin
 * 
 */
public class Answer_atm_into_account implements IService {
	private String bizid;
	private JdbcWorker jw;
	public VO exec(VO args) {
		CommonUtil.debug("Answer_atm_into_account begin");
		try {
			jw = new JdbcWorker();
			bizid = args.getAttr("SERIALNO");
			// 保存影像
			List<String> photoPathList = saveImage(args);
			// 修改cm_djb flag 字段为1
			this.updateFlag(bizid);
			return this.packResult(bizid, args);
		} catch (Exception e) {
			CommonUtil.debug("Answer_atm_into_account  error", e);
			return null;
		}
	}
	
	/**
	 * 修改flag本笔交易的状态
	 * @param bizid
	 * @throws Exception 
	 */
	private void updateFlag(String bizid) throws Exception {
		StringBuffer sql = new StringBuffer(50);
		sql.append("UPDATE cm_djb SET flag='"+Constant.CM_DJB_FLAG_AWAIT+"'  WHERE bizid='" + bizid + "'");
		jw.execute(sql.toString());
	}

	/**
	 * 保存影像并返回影像保存完整路径
	 * 
	 * @param vo
	 * @throws Exception
	 */
	private List<String> saveImage(VO vo) throws Exception {
		String path = Param.getValue("UAI", "bill_photo_save_path");
		List<String> list = new ArrayList<String>();
		if (path != null) {
			int count = Integer.parseInt(vo.getAttr("IMGNUM"));
			path += new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/"; // 按照日期保存
			String filename = vo.getAttr("DEVICENO") + "-" + bizid +"-"+ vo.getAttr("NETNUM") 
					+  "-" + vo.getAttr("BILLTYPE") + "-1002"; 
			if (count > 0) {
				for (int i = 0; i < count; i++) {
					byte[] photo = Base64.decode(vo.getAttr("photo" + (i + 1)));
					String photo1name = filename + "-" + i + ".jpg";
					list.add(photo1name);
					BillPhoto.save(path, photo1name, photo);
				}
			}
		} else {
			CommonUtil.debug("image path is null--影像保存路径为空");
		}
		return list;
	}

	/**
	 * 生成报文
	 * @param args
	 * @return VO
	 * @throws UnsupportedEncodingException 
	 */
	private VO packResult(String bizid, VO arg) throws UnsupportedEncodingException{
		VO vo = new VO();
		StringBuffer message = new StringBuffer(50);
//		message.append("00000000"); // 报文总长度（不包括自身长度），定长，位数不足前补0，全部为0则报文数据为空（不超过4K）
		message.append("00000000"); // 流水号
		message.append("00000000"); // 交易报文总长度 U_char[8]
		message.append("1002"); // 交易码 u_char[4]
		message.append("0000"); // 应答结果 u_char[4]
		String billno = arg.getAttr("BILLNO"); // 票据号码
		String draweebank = arg.getAttr("DRAWEEBANK"); // 开户行交换行号
		String systemtype = arg.getAttr("SYSTEMTYPE"); // 对应集中处理系统的业务类型
		String idcard = arg.getAttr("IDCARD"); // 开户人账号（身份证号？）
		String sucess = "success";
		if (bizid.length() > 0) {
			message.append("00000004R0010000"); // 处理结果代码
//			message += String.format("%08d", sucess.getBytes("gb2312").length) + "R002" + sucess;
			message.append(String.format("%08d", sucess.getBytes("gb2312").length) + "R002" + sucess); // 结果描述
			
			message.append("00000020R003" + bizid); // 业务流水号
			// 返回票据号码
			message.append(String.format("%08d", billno.getBytes("gb2312").length) + "R004" + billno); // 票据号码
//			// 返回付款人账号
			message.append(String.format("%08d", idcard.getBytes("gb2312").length) + "R005" + idcard);
//			// 开户行交换行号
			message.append(String.format("%08d", draweebank.getBytes("gb2312").length) + "R006" + draweebank);
//			// 对应集中处理系统的业务类型
			message.append(String.format("%08d", systemtype.getBytes("gb2312").length) + "R007" + systemtype);
		} else {
			message.append("00000004R0019999");
			String error = "fail";
			message.append(String.format("%08d", error.getBytes("gb2312").length) + "R002" + error);
			message.append("00000004R003" + String.format("%020d", 0));
			// 返回票据号码
			message.append(String.format("%08d", billno.getBytes("gb2312").length) + "R004" + billno); // 票据号码
//			// 返回付款人账号
			message.append(String.format("%08d", idcard.getBytes("gb2312").length) + "R005" + idcard);
//			// 开户行交换行号
			message.append(String.format("%08d", draweebank.getBytes("gb2312").length) + "R006" + draweebank);
//			// 对应集中处理系统的业务类型
			message.append(String.format("%08d", systemtype.getBytes("gb2312").length) + "R007" + systemtype);
		}
		int bodyLen = message.toString().getBytes("gb2312").length;
		message.replace(8, 16, String.format("%08d", bodyLen - 24));
		message.insert(0, String.format("%08d", bodyLen));
		vo.setAttr("msg", message.toString());
		return vo;
	}
	
	
	/**
	 * 保存到本地
	 */
	private void saveLocal (List<String> photoPathList, VO args) {
//		String front_billPath=photoPathList.get(0);
//		String back_billPath=photoPathList.get(1);
//		args.setAttr("front_receiptPath", front_billPath);
//		args.setAttr("back_receiptPath", back_billPath);
//		VO result=SV.g("atm.Savereceiptpath", args);
	}

	
	/**
	 * 持久化数据以备转发集中作业管理中心
	 * @param data
	 * @throws Exception 
	 */
	private void localize(VO arg) throws Exception {
		String data = arg.getAttr("data");
		if (data != null) {
			// 生成ID
			String id = new Date().getTime() + arg.getAttr("DEVICENO");
			// 插入一条记录
			StringBuffer insert_sql = new StringBuffer(100);
			insert_sql.append("INSERT INTO atmp_tempdata(id,bizid,data,flag,type) VALUES ('"+id+"','"+arg.getAttr("SERIALNO")+"',empty_clob(),'0','1002')");
			jw.execute(insert_sql.toString());
			// 更改新增记录的clob字段值
			StringBuffer update_sql = new StringBuffer(100);
			update_sql.append("SELECT data FROM atmp_tempdata WHERE id='"+id+"' for update");
			DBOperation db = null;
			Connection conn = null;
			ResultSet rs = null;
			try {
				db = new DBOperation();
				conn = db.getCon();
				rs = db.getrs(update_sql.toString());
				CLOB clob = null;
				if (rs.next()) {
					clob = (CLOB) rs.getClob(1);
				}
				@SuppressWarnings("deprecation")
				Writer writer = clob.getCharacterOutputStream();
				writer.write(data);
				writer.flush();
				writer.close();
			} finally {
				rs.close();
				conn.commit();
				db.closed();
				db = null;
			}
		} else {
			CommonUtil.debug("data数据为空");
		}
	}
	private long getBizid() throws Exception {
		JdbcWorker j = new JdbcWorker();
		long INSTANCEID = j.getSeqValue("cmdjb_bizid");
		return INSTANCEID;
	}

}
